const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();


Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    TabCur: 0,
    MainCur: 0,
    VerticalNavTop: 0,
    list: [],
    load: true,

    hasLogin: false,
    Administrator: false,
    userInfo: {},
    orderType: '',
    newGoods: [],
    hotGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    channel: [],
    banner:[],
    cartCount: 0,
  },

  onShareAppMessage: function() {
    return {
      title: 'order-meal-wx',
      desc: '唯爱与美食不可辜负',
      path: '/pages/index/index'
    }
  },

  onPullDownRefresh() {
    this.getIndexData();
    //在当前页面显示导航条加载动画
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getIndexData: function() {
    wx.showLoading({
      title: '加载中',
    });

    setTimeout(function() {
      wx.hideLoading()
    }, 2000);

    let that = this;
    util.request(api.IndexUrl).then(function(res) {
      if (res.errno === 0) {
        let floorGoods = res.data.floorGoodsList;
        for(let i = 0; i < floorGoods.length; i++){
          floorGoods[i].index = i;
        }
        that.setData({
          newGoods: res.data.newGoodsList,
          hotGoods: res.data.hotGoodsList,
          topics: res.data.topicList,
          brands: res.data.brandList,
          floorGoods: floorGoods,
          groupons: res.data.grouponList,
          channel: res.data.channel,
          banner: res.data.banner
        });
        wx.hideLoading();
      }
    });
  },

  //添加到购物车
  addToCart: function(e) {
    var that = this;
    let vindex = e.target.dataset.vindex;
    let index = e.target.dataset.index;
    let floorGoods = that.data.floorGoods;
    floorGoods[index].goodsList[vindex].add = true;
    //添加到购物车
    util.request(api.CartOrderAdd, {
      goodsId: floorGoods[index].goodsList[vindex].id,
    }, "POST").then(function(res) {
      if (res.errno == 0) {
        wx.showToast({
          title: '添加成功'
        });
        that.setData({
          floorGoods : floorGoods,
        })
      } else {
        util.showErrorToast(res.errmsg);
      }
    });
  },

  toCart:function() {
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },

  //页面初始化
  onLoad: function(options) {
    var that = this;
    //获取启动小程序场景值，根据场景判断使用模式，到店点餐模式，座位点餐模式，预约点餐模式
    var start_scene = wx.getLaunchOptionsSync().scene;
    // var start_scene = 1047;      //测试数据

    //座位点餐模式页面初始化通过扫描普通二维码携带的参数
    // var start_scene = 1011;      //测试数据
    // options.q = "A1";            //测试数据
    
    if (start_scene == 1047){
      app.globalData.orderType = "到店点餐";
      that.setData({ 
        orderType : "到店点餐",
      })
    }else if (start_scene == 1011){
      if(options.q){
        const q = decodeURIComponent(options.q)
        app.globalData.orderType = q.substring((q.indexOf("="))+1,q.length);
        that.setData({ 
          orderType : "座位号：" + q.substring((q.indexOf("="))+1,q.length),
        })
      }else{
        app.globalData.orderType = "到店点餐";
        that.setData({ 
          orderType : "到店点餐",
        })
      }
    } else { 
      app.globalData.orderType = "预约模式";
      that.setData({ 
        orderType : "预约模式",
      })
    }

    if (options.scene) {
      var scene = decodeURIComponent(options.scene);
      console.log("scene:" + scene);

      let info_arr = [];
      info_arr = scene.split(',');
      let _type = info_arr[0];
      let id = info_arr[1];

      if (_type == 'goods') {
        wx.navigateTo({
          url: '../goods/goods?id=' + id
        });
      } else if (_type == 'groupon') {
        wx.navigateTo({
          url: '../goods/goods?grouponId=' + id
        });
      } else {
        wx.navigateTo({
          url: '../index/index'
        });
      }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?grouponId=' + options.grouponId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?id=' + options.goodId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.orderId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
      });
    }
    this.getIndexData();
  },

  onReady: function() {
    wx.hideLoading()
    // 页面渲染完成
  },
  onShow: function() {
    // 页面显示
    //获取用户的登录信息
    if (app.globalData.hasLogin) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        userInfo: userInfo,
        hasLogin: true
      });
      //管理员登录
      if (app.globalData.Administrator) {
        this.setData({
          Administrator: true
        });
      }
    }

    this.getIndexData();
    
    //自定义底部导航栏高亮显示不加会导致高亮随机跳
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.index,
      MainCur: e.currentTarget.dataset.index,
      VerticalNavTop: (e.currentTarget.dataset.index - 1) * 50
    })
  },
  VerticalMain(e) {
    let that = this;
    let floorGoods = this.data.floorGoods;
    let tabHeight = 0;
    if (this.data.load) {
      for (let i = 0; i < floorGoods.length; i++) {
        let view = wx.createSelectorQuery().select("#main-" + i);
        view.fields({
          size: true
        }, data => {
          floorGoods[i].top = tabHeight;
          tabHeight = tabHeight + data.height;
          floorGoods[i].bottom = tabHeight;     
        }).exec();
      }
      that.setData({
        load: false,
        floorGoods: floorGoods
      })
    }

    let scrollTop = e.detail.scrollTop + 20;
    for (let i = 0; i < floorGoods.length; i++) {
      if (scrollTop > floorGoods[i].top && scrollTop < floorGoods[i].bottom) {
        that.setData({
          VerticalNavTop: (floorGoods[i].index - 1) * 50,
          TabCur: floorGoods[i].index
        })
        return false
      }
    }
  }

})